<template>
  <g-upload
    class="g-mr12"
    :action="props.uploadApi"
    :show-file-list="false"
    :limit="1"
    :name="name"
    :post-params="params"
    accept=".xlsx, .xls"
    @success="handleUploadSuccess"
  >
    <template #default="{ loading: btnLoading }">
      <el-button type="primary" :loading="btnLoading"
        ><CIcon type="c-xian-daoru" class="g-mr4"></CIcon>{{ uploadText }}</el-button
      >
    </template>
  </g-upload>
  <el-button type="default" @click="handleDownloadTemplate" v-if="hasTemplateDownload">
    <CIcon class="g-mr4" type="c-xian-xiazai"></CIcon>
    下载模板</el-button
  >
</template>
<script lang="ts">
export default {
  name: 'FileUploadAndTempDownload'
};
</script>
<script lang="ts" setup>
import { withDefaults, defineProps, defineEmits } from 'vue';
import { GUpload } from '@/components/GUpload';
import { HTTP_RESPONSE_CODE } from '@/constants';
import { useMessage } from '@/hooks/useMessage';

interface CFileUploadAndTempDownloadProps {
  /**
   * 上传接口api
   */
  uploadApi: string;
  /**
   * 上传参数
   */
  params: Record<string, any>;
  /**
   * 是否有模板下载
   */
  hasTemplateDownload?: boolean;
  /**
   * 模板url
   */
  templateUrl?: string;
  /**
   * 上传按钮文案
   */
  uploadText?: string;
  /**
   * 文件字段
   */
  name?: string;
}

const props = withDefaults(defineProps<CFileUploadAndTempDownloadProps>(), {
  hasTemplateDownload: true,
  templateUrl: '',
  uploadText: '批量导入',
  name: 'fileInfo'
});
const emits = defineEmits(['success']);

const { createMessage } = useMessage();

/**
 * 导入成功
 */
const handleUploadSuccess = (file: any) => {
  if (file?.response?.code === HTTP_RESPONSE_CODE.OK_CODE) {
    createMessage.success(`${props.uploadText}成功`);
    emits('success');
  }
};

/**
 * 模板文件下载
 */
function handleDownloadTemplate() {
  if (!props.templateUrl) {
    createMessage.success('模板url不存在！');
    return;
  }
  window.open(props.templateUrl);
}
</script>
